package com.fjut.zr.judge_system.Config.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fjut.zr.judge_system.Config.interceptor.annotation.LogAnnotation;
import com.fjut.zr.judge_system.Util.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Objects;

@Component
@Aspect //切面 定义了和切点的关系
@Slf4j
public class LogAspect {

    @Value("${oj.config.aopLog.enable}")
    private boolean interceptorLogEnable;
    @Pointcut("@annotation(com.fjut.zr.judge_system.Config.interceptor.annotation.LogAnnotation)")
    public void pt(){}
    //环绕通知
    @Around("pt()")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        long beginTime=System.currentTimeMillis();
        //执行方法
        Object result= joinPoint.proceed();
        //执行时长
        long time=System.currentTimeMillis()-beginTime;
        //保存日志
        recordLog(joinPoint,time,new Timestamp(System.currentTimeMillis()));
        return result;
    }
    public void recordLog(ProceedingJoinPoint joinPoint, long time, Timestamp date){
        MethodSignature signature=(MethodSignature)joinPoint.getSignature();
        Method method=signature.getMethod();
        LogAnnotation logAnnotation=method.getAnnotation(LogAnnotation.class);
        //请求的方法名
        String className=joinPoint.getTarget().getClass().getName();
        String methodName=signature.getName();
        //请求参数
        Object[] args=joinPoint.getArgs();
        Object[] arguments  = new Object[args.length];
        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof ServletRequest || args[i] instanceof ServletResponse || args[i] instanceof MultipartFile) {
                //ServletRequest不能序列化，从入参里排除，否则报异常：java.lang.IllegalStateException: It is illegal to call this method if the current request is not in asynchronous mode (i.e. isAsyncStarted() returns false)
                //ServletResponse不能序列化 从入参里排除，否则报异常：java.lang.IllegalStateException: getOutputStream() has already been called for this response
                continue;
            }
            arguments[i] = args[i];
        }
        String paramter = "";
        if (arguments != null) {
            try {
                paramter = JSONObject.toJSONString(arguments);
            } catch (Exception e) {
                paramter = arguments.toString();
            }
        }
        HttpServletRequest request=((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        if (interceptorLogEnable) {
            String s = "\n===================日志开始==========================\n"
                    + String.format("== 【模块名称】:%s\n", logAnnotation.module())
                    + String.format("== 【操作名称】:%s\n", logAnnotation.operator())
                    + String.format("== 【请求时间】:%s\n", date)
                    + String.format("== 【请求方法名】:%s\n", className + "." + methodName + "()")
                    + String.format("== 【请求IP】:%s\n", IpUtils.getClientIpAddress(request))
                    + String.format("== 【请求内容】:%s\n", paramter)
                    + String.format("== 【执行时间】：%s\n", time)
                    + "=======================日志结束=====================\n";
            log.info(s);
        }
    }
}
